
package com.android.fitnesscenter.view.server;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.server.QueryService;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.ConfigProperties.QueryDetailResult;
import com.android.fitnesscenter.utils.ConfigProperties.TradingType;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.MapEntity;
import com.android.fitnesscenter.utils.ToastHelper;
import com.android.fitnesscenter.utils.ViewHelper;
import com.android.fitnesscenter.view.BaseActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class ServerMainActivity extends BaseActivity implements OnClickListener {

    // private GifView gif_main;

    @ViewInject(R.id.btn_pay)
    private Button btn_pay;

    @ViewInject(R.id.btn_top_up)
    private Button btn_top_up;

    @ViewInject(R.id.edtxt_pay_money)
    private EditText edtxt_pay_money;

    @ViewInject(R.id.edtxt_top_up_money)
    private EditText edtxt_top_up_money;

    private LinearLayout llayout_new_user, llayout_query_detail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_main_layout);
        ViewUtils.inject(this);
        initTitleBar(getString(R.string.txt_operate), true);
        ibtn_back.setBackgroundResource(R.drawable.icon_logout);
        ibtn_more.setBackgroundResource(R.drawable.icon_setting);
        ibtn_more.setVisibility(View.VISIBLE);
        // gif_main = (GifView) findViewById(R.id.gif_main);
        // gif_main.setGifImageType(GifImageType.COVER);
        // gif_main.setGifImage(R.drawable.server_main_bg);

        llayout_new_user = (LinearLayout) findViewById(R.id.llayout_new_user);
        llayout_new_user.setOnClickListener(this);
        llayout_query_detail = (LinearLayout) findViewById(R.id.llayout_query_detail);
        llayout_query_detail.setOnClickListener(this);

        isCheckVersion = true;
        setWifiDialog();
        edtxt_pay_money.addTextChangedListener(mPayTextWatcher);

        edtxt_top_up_money.addTextChangedListener(mTopUpTextWatcher);

    }

    private TextWatcher mTopUpTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null) {
                String temp = s.toString();
                if (!TextUtils.isEmpty(temp)) {
                    if (temp.contains(".")) {
                        int x = 0;
                        for (int i = 0; i <= temp.length() - 1; i++) {
                            String getstr = temp.substring(i, i + 1);
                            if (getstr.equals(".")) {
                                x++;
                                if (x == 2) {
                                    edtxt_top_up_money.removeTextChangedListener(this);
                                    temp = temp.substring(0, temp.length() - 1);
                                    edtxt_top_up_money.setText(temp);
                                    edtxt_top_up_money.setSelection(temp.length());
                                    edtxt_top_up_money.addTextChangedListener(mTopUpTextWatcher);
                                    return;
                                }
                            }
                        }
                    }
                    if (!temp.startsWith(".")) {
                        float curMoney = Float.parseFloat(temp);
                        if (curMoney >= 99999.99) {
                            curMoney = 99999.99f;
                            edtxt_top_up_money.removeTextChangedListener(this);
                            temp = "" + 99999.99;
                            edtxt_top_up_money.setText(temp);
                            edtxt_top_up_money.setSelection(temp.length());
                            ToastHelper.getInstance().showShortMsg("最大金额为99999.99!");
                            edtxt_top_up_money.addTextChangedListener(mTopUpTextWatcher);
                        } else {
                            int posDot = temp.indexOf(".");
                            if (posDot <= 0) return;
                            if (temp.length() - posDot - 1 > 2) {
                                s.delete(posDot + 3, posDot + 4);
                            }
                        }
                    } else {
                        edtxt_top_up_money.removeTextChangedListener(this);
                        temp = "0" + temp;
                        edtxt_top_up_money.setText(temp);
                        edtxt_top_up_money.setSelection(temp.length());
                        edtxt_top_up_money.addTextChangedListener(mTopUpTextWatcher);
                    }
                }
            }
        }
    };

    private TextWatcher mPayTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null) {
                String temp = s.toString();
                if (!TextUtils.isEmpty(temp)) {
                    if (temp.contains(".")) {
                        int x = 0;
                        for (int i = 0; i <= temp.length() - 1; i++) {
                            String getstr = temp.substring(i, i + 1);
                            if (getstr.equals(".")) {
                                x++;
                                if (x == 2) {
                                    edtxt_pay_money.removeTextChangedListener(this);
                                    temp = temp.substring(0, temp.length() - 1);
                                    edtxt_pay_money.setText(temp);
                                    edtxt_pay_money.setSelection(temp.length());
                                    edtxt_pay_money.addTextChangedListener(mPayTextWatcher);
                                    return;
                                }
                            }
                        }
                    }
                    if (!temp.startsWith(".")) {
                        float curMoney = Float.parseFloat(temp);
                        if (curMoney >= 99999.99) {
                            curMoney = 99999.99f;
                            edtxt_pay_money.removeTextChangedListener(this);
                            temp = "" + 99999.99;
                            edtxt_pay_money.setText(temp);
                            edtxt_pay_money.setSelection(temp.length());
                            ToastHelper.getInstance().showShortMsg("最大金额为99999.99!");
                            edtxt_pay_money.addTextChangedListener(mPayTextWatcher);
                        } else {
                            int posDot = temp.indexOf(".");
                            if (posDot <= 0) return;
                            if (temp.length() - posDot - 1 > 2) {
                                s.delete(posDot + 3, posDot + 4);
                            }
                        }
                    } else {
                        edtxt_pay_money.removeTextChangedListener(this);
                        temp = "0" + temp;
                        edtxt_pay_money.setText(temp);
                        edtxt_pay_money.setSelection(temp.length());
                        edtxt_pay_money.addTextChangedListener(mPayTextWatcher);
                    }
                }
            }
        }
    };

    @Override
    protected void ibtn_back() {
        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                logout();
            }
        };
        new ViewHelper(ServerMainActivity.this).showBTN2Dialog("提示", "是否退出此账号?", "确定", "取消", positiveListener,
                null, null);
    }

    @OnClick(R.id.btn_pay)
    public void btn_pay(View view) {
        if (edtxt_pay_money == null || edtxt_pay_money.getText() == null) {
            return;
        }
        payMoney = edtxt_pay_money.getText().toString();
        if (TextUtils.isEmpty(payMoney)) {
            ToastHelper.getInstance().showShortMsg("请输入缴费金额!");
        } else {
            queryRecordsAdm(FROM_SERVER_MAIN_PAY_ACTIVITY, TradingType.PAY);
        }
    }

    private String topUpMoney;
    private String payMoney;

    @OnClick(R.id.btn_top_up)
    public void btn_top_up(View view) {
        if (edtxt_top_up_money == null || edtxt_top_up_money.getText() == null) {
            return;
        }
        topUpMoney = edtxt_top_up_money.getText().toString();
        if (TextUtils.isEmpty(topUpMoney)) {
            ToastHelper.getInstance().showShortMsg("请输入充值金额!");
        } else {
            queryRecordsAdm(FROM_SERVER_MAIN_TOP_UP_ACTIVITY, TradingType.TOP_UP);
        }
    }

    @Override
    protected void parseQueryRecordsAdmResult(int fromActivity, final MapEntity entity) {
        if (fromActivity == FROM_SERVER_MAIN_TOP_UP_ACTIVITY) {
            if (entity == null || entity.isEmpty()) {
                saveNewInfo(topUpMoney, TradingType.TOP_UP);
            } else {
                DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ignoreByAdmin(entity.getString(QueryDetailResult.ID));
                    }
                };
                new ViewHelper(ServerMainActivity.this).showBTN2Dialog("提示", "存在用户没有确认的充值操作", "删除", "忽略",
                        positiveListener, null, null);
            }
        } else if (fromActivity == FROM_SERVER_MAIN_PAY_ACTIVITY) {
            if (entity == null || entity.isEmpty()) {
                saveNewInfo(payMoney, TradingType.PAY);
            } else {
                DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ignoreByAdmin(entity.getString(QueryDetailResult.ID));
                    }
                };
                new ViewHelper(ServerMainActivity.this).showBTN2Dialog("提示", "存在用户没有确认的扣款操作", "删除", "忽略",
                        positiveListener, null, null);
            }
        }
    }

    private void ignoreByAdmin(String id) {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", getIMEI());
        params.addBodyParameter("id", id);
        String url = ConfigProperties.SERVICE_URL + "ignoreByAdmin.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerMainActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("加载中,请等待...");
                mDialog.show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerMainActivity.this != null && !ServerMainActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                String msg = jsonObject.getString("message");
                                if (success) {
                                    ToastHelper.getInstance().showShortMsg(msg);
                                } else {
                                    new ViewHelper(ServerMainActivity.this).showBTNDialog(msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerMainActivity.this).showBTNDialog("加载失败,请重试!");
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                if (ServerMainActivity.this != null && !ServerMainActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    new ViewHelper(ServerMainActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    private void saveNewInfo(String money, final String type) {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", getIMEI());
        params.addBodyParameter("money", money);
        params.addBodyParameter("type", type);

        String url = ConfigProperties.SERVICE_URL + "saveNewInfo.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerMainActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("加载中,请等待...");
                mDialog.show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerMainActivity.this != null && !ServerMainActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                if (success) {
                                    if (TextUtils.equals(type, TradingType.PAY)) {
                                        ToastHelper.getInstance().showShortMsg("缴费信息已发送,需要用户确认!");
                                        edtxt_pay_money.setText("");
                                    } else {
                                        ToastHelper.getInstance().showShortMsg("充值信息已发送,需要用户确认!");
                                        edtxt_top_up_money.setText("");
                                    }
                                    if (!isServiceRun(ServerMainActivity.this,
                                            "com.android.fitnesscenter.server.QueryService")) {
                                        Intent intent = new Intent(ServerMainActivity.this, QueryService.class);
                                        startService(intent);
                                    }
                                } else {
                                    String msg = jsonObject.getString("message");
                                    new ViewHelper(ServerMainActivity.this).showBTNDialog(msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerMainActivity.this).showBTNDialog("加载失败,请重试!");
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                if (ServerMainActivity.this != null && !ServerMainActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    new ViewHelper(ServerMainActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    @Override
    protected void titlebarMethod(int id) {
        switch (id) {
            case R.id.ibtn_more:
                Intent intent = new Intent(this, ServerSettingActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llayout_new_user:
                queryLockedUsers(FROM_MAIN_ACTIVITY);
                break;
            case R.id.llayout_query_detail:
                Intent intent1 = new Intent(this, ServerQueryDetailListActivity.class);
                startActivity(intent1);
                break;
        }
    }

    @Override
    protected void queryLockedUsersResult() {
        super.queryLockedUsersResult();
        if (mUserList != null && mUserList.size() > 0) {
            Intent intent = new Intent(this, ServerUnLockActivity.class);
            startActivity(intent);
        } else {
            ToastHelper.getInstance().showShortMsg("没有新用户存在!");
        }
    }

}
